package com.example.config;

import com.alibaba.fastjson.JSON;
import com.example.entity.vo.UsrRole;
import com.example.service.ISysUserService;
import com.example.ulit.JwtUtil;
//import com.example.ulit.UsrIdByToken;
//import io.netty.util.internal.StringUtil;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.authority.AuthorityUtils;
//import org.springframework.security.core.context.SecurityContext;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//import org.springframework.stereotype.Component;
//import org.springframework.util.StringUtils;
import com.example.ulit.UsrIdByToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class JWTFilter extends OncePerRequestFilter {

    @Resource
    UsrIdByToken usrIdByToken;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        String path = request.getRequestURI();
        String method = request.getMethod();
        if("/uni-app/sys-user/sendMessage".equals(path) || "/uni-app/sys-user/insert".equals(path)){
            filterChain.doFilter(request,response);
            return;
        }
        if("/login".equals(path) && "POST".equals(method)){
            filterChain.doFilter(request,response);
            return;
        }
        String token = request.getHeader("Authorization").replace("Bearer","");//1.从请求头中获取token令牌
        System.out.println(token);
        if (!StringUtils.hasText(token)){
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("code","401");
            resultMap.put("msg","您还没有登录呢，请登录后访问!");
            PrintWriter out = response.getWriter();
            out.print(JSON.toJSON(resultMap));
            out.flush();
            out.close();
            return;
        }
        if (!JwtUtil.verify()){
            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("code","500");
            resultMap.put("msg","token已失效");
            PrintWriter out = response.getWriter();
            out.print(JSON.toJSON(resultMap));
            out.flush();
            out.close();
            return;
        }
        SecurityContext context = SecurityContextHolder.getContext();
        Map<String,Object> userInfo = JwtUtil.parseToken(token);
        Object userName = userInfo.get("usrName");
        String pwd = userInfo.get("password").toString();
        usrIdByToken.getStringRedisTemplate(token);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList("ROLE_"+ userInfo.get("roleName").toString());
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName,new BCryptPasswordEncoder()
                .encode(pwd),authorityList);
        context.setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
